package com.woniu.woniu_bx.controller;

import com.woniu.woniu_bx.pojo.ResponseEntity;
import com.woniu.woniu_bx.service.UserService;
import com.woniu.woniu_bx.utils.OssManagerUtil;
import com.woniu.woniu_bx.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Description 图片测试
 * @Author zhangjin
 * @Date 2022/8/31 19:35
 */
@RestController
@RequestMapping
public class UploadController {
    @Autowired
    private UserService userService;

    @RequestMapping("/upload")
    public ResponseEntity uploadImg(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return ResponseEntity.FAIL("文件找不到", null);
        }
        // 获取图片后缀
        String submittedFileName = file.getOriginalFilename();
        String suffix = submittedFileName.substring(submittedFileName.lastIndexOf("."));
        // 图片随机前缀
        String fileName = RandomUtil.getImgRandom();
        // 拼接文件名
        String url = OssManagerUtil.uploadImage(fileName + suffix, file.getSize(), file.getInputStream());
        return ResponseEntity.SUCCESS("上传成功", url);
    }

    /**
     * 根据图片路径删除数据库
     *
     * @param url
     * @return
     */
    @RequestMapping("/delete/image/")
    public ResponseEntity deleteImage(String url) {
        userService.deleteImage(url);
        return ResponseEntity.SUCCESS("删除成功", null);
    }
}
